import { OnInit, Component, Output, EventEmitter, ViewChild } from '@angular/core';
import { NzMessageService } from 'ng-zorro-antd';
import { CourseTypeService } from 'src/app/project/service/icm/icm-base/course-type/course-type.service';
import { FormBuilder, Validators, NgForm, FormGroup, FormControl, ValidationErrors } from '@angular/forms';
import { OperationNotification, OperationType } from 'src/app/project/model/common/operation-notification';
import { CourseTypeDTO } from 'src/app/project/model/icm/icm-base/course-type/course-type.dto';
import { QueryOptions } from 'src/app/project/model/common/query-options';
import { Observer, Observable } from 'rxjs';
import { FormUtil } from '@shared/utils/form-util';

@Component({
  selector: 'app-course-type-detail',
  templateUrl: './course-type-detail.component.html',
  styles: [],
})
export class CourseTypeDetailComponent implements OnInit {
  constructor(private msg: NzMessageService, private courseTypeService: CourseTypeService, private fb: FormBuilder) {
    this.validateForm = this.fb.group({
      code: ['', [Validators.required], [this.codeAsyncValidator]],
      name: ['', [Validators.required]],
      showOrder: ['', [Validators.required]],
      courseBaseType: [''],
    });
  }

  /**
   * 数据变化通知事件
   */
  @Output()
  notification = new EventEmitter<OperationNotification<CourseTypeDTO>>();

  /**
   * form组件
   */
  @ViewChild('courseTypeForm', { static: false })
  public courseTypeForm: NgForm;

  /**
   * 表单
   */
  validateForm: FormGroup;

  /**
   * 是否预览
   */
  isPreView = false;

  /**
   * 表单窗体打开/关闭控制
   */
  isVisible = false;

  /**
   * 调用后台API标志
   */
  loading = false;

  /**
   * 分页参数初始化
   */
  queryOptions: QueryOptions = {
    page: 0,
    size: 20,
    sort: 'id,asc',
  };

  /**
   * 课程类型信息
   */
  courseType: CourseTypeDTO = {
    id: null,
    code: null,
    name: null,
    courseBaseType: null,
    showOrder: 0,
  };

  /**
   * 课程类型编码是否已存在，true为已存在
   */
  isExist: boolean;

  /**
   * 校验课程类型编码
   */
  codeAsyncValidator = (control: FormControl) =>
    new Observable((observer: Observer<ValidationErrors | null>) => {
      setTimeout(() => {
        this.courseTypeService.checkoutCodeIsExist(control.value).subscribe(data => {
          this.isExist = data.data;
        });
        if (this.isExist) {
          observer.next({ error: true, duplicated: true });
        } else if (control.value.includes(' ')) {
          observer.next({ error: true, blank: true });
        } else {
          observer.next(null);
        }
        observer.complete();
      }, 1000);
    });

  /**
   * 修改窗口状态
   */
  handleCancel() {
    this.isVisible = false;
    FormUtil.resetForm(this.courseTypeForm.form);
  }

  /**
   * 修改或新增课程类型信息
   * @param isPreView 是否预览
   * @param item 课程类型信息
   */
  edit(isPreView: boolean, item: CourseTypeDTO) {
    this.isPreView = isPreView;

    this.courseType = this.initCourseType(item);
    this.isVisible = true;
  }

  /**
   * 初始化课程类型
   */
  initCourseType(item: CourseTypeDTO): CourseTypeDTO {
    return {
      id: item ? item.id : null,
      name: item ? item.name : null,
      code: item ? item.code : null,
      showOrder: item ? item.showOrder : 0,
      courseBaseType: item ? item.courseBaseType : null,
    };
  }

  /**
   * 保存前验证数据
   */
  beforeSave() {
    if (this.courseType.code === '') {
      this.msg.error('课程类型编码必填');
      return false;
    }
    if (this.courseType.name === '') {
      this.msg.error('课程类型名称必填');
      return false;
    }
    if (!this.courseType.showOrder && this.courseType.showOrder !== 0) {
      this.msg.error('显示顺序必填');
      return false;
    }
    return true;
  }

  /**
   * 保存
   */
  save() {
    if (!this.beforeSave()) {
      return;
    }
    this.loading = true;
    if (!this.courseType.id) {
      // id为空，为新建
      this.courseTypeService.create(this.courseType).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('保存失败，请重试'),
        () => this.afterCallCompleted(),
      );
    } else {
      // id不为空，为修改
      this.courseTypeService.complete(this.courseType.id, this.courseType).subscribe(
        data => this.afterItemSaved(data, OperationType.CREATE),
        () => this.msg.error('修改失败，请重试'),
        () => this.afterCallCompleted(),
      );
    }
  }

  /**
   * 数据保存后的通用操作
   *
   * @param data 保存的数据
   * @param operation 操作类型
   */
  private afterItemSaved(data: CourseTypeDTO, operation: OperationType): void {
    this.loading = false;
    this.handleCancel();
    this.notification.emit({
      operation,
      data,
    });
    this.msg.success('保存成功!');
  }

  /**
   * API调用完成后的操作
   */
  private afterCallCompleted(): void {
    this.loading = false;
  }

  ngOnInit() {}
}
